import { useMedicalStore } from '@/store/medical';

export class WebSocketHandler {
  constructor() {
    this.socket = null;
    this.connectionPromise = null;
    this.onMessageUpdate = null;
    this.fullMessage = '';
    this.medicalStore = useMedicalStore();
  }

  handleOpen = () => {
    console.log('WebSocket 连接已打开');
    this.connectionPromise?.resolve?.(this.socket);
  }

  handleMessage = (event) => {
    console.log('接收到消息:', event.data);

    try {
      const data = JSON.parse(event.data);
      const content = data.content;

      if (content.includes('[DONE]')) {
        this.medicalStore.saveResponse(this.fullMessage);
        this.onMessageUpdate?.(this.fullMessage);
        this.fullMessage = '';
      } else {
        this.fullMessage += content;
        this.onMessageUpdate?.(this.fullMessage);
      }
    } catch (error) {
      console.error('Error processing message:', error);
    }
  }

  handleError = (error) => {
    console.error('WebSocket 连接发生错误:', error);
    this.connectionPromise = null;
    this.connectionPromise?.reject?.(error);
  }

  handleClose = () => {
    console.log('WebSocket 连接已关闭');
    this.connectionPromise = null;
  }

  setMessageCallback(callback) {
    this.onMessageUpdate = callback;
  }
}
